<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="$router.go(-1)"></i>
      <span>商品管理</span>
      <i class="fa fa-plus" @click="addFood" title="新增商品"></i>
    </header>

    <!-- 商品列表 -->
    <div class="food-list" v-if="foodList.length > 0">
      <div 
        class="food-item" 
        v-for="food in foodList" 
        :key="food.foodId"
      >
        <img :src="getFoodImage(food.foodId)" alt="商品图片">
        <div class="food-info">
          <div class="food-info-header">
            <h3>{{ food.foodName }}</h3>
            <div class="food-price">¥{{ food.foodPrice }}</div>
          </div>
          <p class="food-explain">{{ food.foodExplain || '暂无描述' }}</p>
          <div class="food-actions">
            <button class="btn-edit" @click="editFood(food)">
              <i class="fa fa-edit"></i> 编辑
            </button>
            <button class="btn-delete" @click="deleteFood(food)">
              <i class="fa fa-trash"></i> 删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载中状态 -->
    <div v-else-if="loading" class="loading">
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty">
      <i class="fa fa-cutlery"></i>
      <p>暂无商品，点击右上角添加商品</p>
      <button class="btn-add-empty" @click="addFood">添加第一个商品</button>
    </div>

    <!-- 商品编辑弹窗 -->
    <div class="modal-overlay" v-if="showEditModal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ editingFood.foodId ? '编辑商品' : '新增商品' }}</h3>
          <i class="fa fa-times" @click="closeModal"></i>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>商品名称：</label>
            <input 
              type="text" 
              v-model="editingFood.foodName" 
              placeholder="请输入商品名称"
              maxlength="50"
            />
          </div>
          <div class="form-group">
            <label>商品价格：</label>
            <input 
              type="number" 
              v-model="editingFood.foodPrice" 
              placeholder="请输入商品价格"
              min="0"
              step="0.01"
            />
          </div>
          <div class="form-group">
            <label>商品描述：</label>
            <textarea 
              v-model="editingFood.foodExplain" 
              placeholder="请输入商品描述（可选）"
              rows="3"
              maxlength="200"
            ></textarea>
          </div>
          <div class="form-group">
            <label>备注信息：</label>
            <input 
              type="text" 
              v-model="editingFood.remarks" 
              placeholder="备注信息（可选）"
              maxlength="100"
            />
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-cancel" @click="closeModal">取消</button>
          <button class="btn-save" @click="saveFood" :disabled="!canSave">
            {{ editingFood.foodId ? '保存' : '添加' }}
          </button>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>

import { useRouter } from "vue-router";
import { ref, inject, onMounted, computed } from "vue";
import { getSessionStorage } from "../common.js";
import qs from "qs";

// 导入商品图片
import sp01 from '@/assets/sp01.png'
import sp02 from '@/assets/sp02.png'
import sp03 from '@/assets/sp03.png'
import sp04 from '@/assets/sp04.png'
import sp05 from '@/assets/sp05.png'
import sp06 from '@/assets/sp06.png'
import sp07 from '@/assets/sp07.png'
import sp08 from '@/assets/sp08.png'
import sp09 from '@/assets/sp09.png'
import sp10 from '@/assets/sp10.png'
import sp11 from '@/assets/sp11.png'
import sp12 from '@/assets/sp12.png'

const axios = inject("axios");
const router = useRouter();

const business = ref(null);
const foodList = ref([]);
const loading = ref(true);
const showEditModal = ref(false);
const editingFood = ref({
  foodId: null,
  foodName: '',
  foodPrice: '',
  foodExplain: '',
  remarks: '',
  businessId: null
});

// 获取商品图片
const getFoodImage = (foodId) => {
  const imageMap = {
    1: sp01, 2: sp02, 3: sp03, 4: sp04, 5: sp05, 6: sp06,
    7: sp07, 8: sp08, 9: sp09, 10: sp10, 11: sp11, 12: sp12
  }
  return imageMap[(foodId % 12) + 1] || sp01
}

// 计算是否可以保存
const canSave = computed(() => {
  return editingFood.value.foodName.trim() !== '' && 
         editingFood.value.foodPrice > 0;
});

// 加载商品列表
const loadFoodList = async () => {
  if (!business.value) return;
  
  loading.value = true;
  try {
    const response = await axios.get(`/api/FoodController/listFoodByBusinessId?businessId=${business.value.businessId}`);
    if (response && Array.isArray(response)) {
      foodList.value = response;
      console.log("加载商品列表成功，共", response.length, "个商品");
    } else {
      foodList.value = [];
      console.log("商品列表为空");
    }
  } catch (error) {
    console.error("加载商品列表失败:", error);
    alert("加载商品列表失败，请刷新重试");
    foodList.value = [];
  } finally {
    loading.value = false;
  }
};

// 新增商品
const addFood = () => {
  editingFood.value = {
    foodId: null,
    foodName: '',
    foodPrice: '',
    foodExplain: '',
    remarks: '',
    businessId: business.value.businessId
  };
  showEditModal.value = true;
};

// 编辑商品
const editFood = (food) => {
  editingFood.value = {
    foodId: food.foodId,
    foodName: food.foodName,
    foodPrice: food.foodPrice,
    foodExplain: food.foodExplain || '',
    remarks: food.remarks || '',
    businessId: food.businessId
  };
  showEditModal.value = true;
};

// 删除商品
const deleteFood = async (food) => {
  if (!confirm(`确定要删除商品"${food.foodName}"吗？`)) {
    return;
  }
  
  try {
    const response = await axios.post(
      "/api/FoodController/deleteFoodById",
      qs.stringify({
        foodId: food.foodId
      })
    );
    
    console.log("删除商品响应:", response);
    
    if (response && response.code === 1) {
      alert("商品删除成功！");
      // 重新加载商品列表
      loadFoodList();
    } else {
      alert(response.error || "删除商品失败！");
    }
  } catch (error) {
    console.error("删除商品失败:", error);
    alert("删除商品失败，请重试");
  }
};

// 保存商品
const saveFood = async () => {
  // 验证数据
  if (!editingFood.value.foodName.trim()) {
    alert("商品名称不能为空！");
    return;
  }
  
  if (!editingFood.value.foodPrice || editingFood.value.foodPrice <= 0) {
    alert("商品价格必须大于0！");
    return;
  }
  
  const isEditing = !!editingFood.value.foodId;
  const apiUrl = isEditing ? "/api/FoodController/updateFood" : "/api/FoodController/saveFood";
  
  try {
    const requestData = {
      foodName: editingFood.value.foodName.trim(),
      foodPrice: parseFloat(editingFood.value.foodPrice),
      foodExplain: editingFood.value.foodExplain.trim(),
      remarks: editingFood.value.remarks.trim(),
      businessId: editingFood.value.businessId
    };
    
    if (isEditing) {
      requestData.foodId = editingFood.value.foodId;
    }
    
    console.log("保存商品请求数据:", requestData);
    
    const response = await axios.post(apiUrl, qs.stringify(requestData));
    
    console.log("保存商品响应:", response);
    
    if (response && response.code === 1) {
      alert(response.message || (isEditing ? "商品修改成功！" : "商品添加成功！"));
      closeModal();
      // 重新加载商品列表
      loadFoodList();
    } else {
      alert(response.error || (isEditing ? "商品修改失败！" : "商品添加失败！"));
    }
  } catch (error) {
    console.error("保存商品失败:", error);
    alert("保存商品失败，请重试");
  }
};

// 关闭弹窗
const closeModal = () => {
  showEditModal.value = false;
  editingFood.value = {
    foodId: null,
    foodName: '',
    foodPrice: '',
    foodExplain: '',
    remarks: '',
    businessId: null
  };
};

// 页面初始化
onMounted(() => {
  // 检查登录状态
  const businessInfo = getSessionStorage("business");
  if (!businessInfo) {
    alert("请先登录！");
    router.push({ path: '/businessLogin' });
    return;
  }
  
  business.value = businessInfo;
  console.log("当前登录商家:", business.value);
  
  // 加载商品列表
  loadFoodList();
});
</script>

<style scoped>
.wrapper {
  width: 100%;
  max-width: 100vw;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
  box-sizing: border-box;
  overflow-x: hidden;
}

/* header样式 */
header {
  width: 100%;
  max-width: 100vw;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.5vw;
  box-sizing: border-box;
  
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
}

header .fa-angle-left {
  font-size: 5.5vw;
  cursor: pointer;
  color: #fff;
}

header span {
  flex: 1;
  text-align: center;
  font-weight: bold;
}

header .fa-plus {
  font-size: 5vw;
  cursor: pointer;
  color: #fff;
}

/* 商品列表样式 */
.food-list {
  width: 100%;
  max-width: 100vw;
  background-color: #fff;
  margin-top: 12vw;
  padding-bottom: 2vw;
  min-height: calc(100vh - 12vw - 20px);
  box-sizing: border-box;
}

.food-item {
  width: 100%;
  max-width: 100%;
  padding: 3vw;
  border-bottom: 1px solid #f0f0f0;
  box-sizing: border-box;
  
  display: flex;
  align-items: flex-start;
  gap: 3vw;
}

.food-item img {
  width: 15vw;
  height: 15vw;
  border-radius: 2vw;
  flex-shrink: 0;
}

.food-info {
  flex: 1;
  min-width: 0;
}

.food-info-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 2vw;
  gap: 2vw;
}

.food-info-header h3 {
  font-size: 3.5vw;
  color: #333;
  margin: 0;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.food-price {
  font-size: 3.5vw;
  font-weight: bold;
  color: #ff6b35;
  flex-shrink: 0;
  white-space: nowrap;
}

.food-explain {
  font-size: 2.8vw;
  color: #999;
  margin: 0 0 1.5vw 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

.food-actions {
  display: flex;
  gap: 2vw;
  margin-top: 1vw;
}

.food-actions button {
  flex: 1;
  height: 7vw;
  border: none;
  border-radius: 1vw;
  font-size: 2.8vw;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 15vw;
  white-space: nowrap;
}

.btn-edit {
  background-color: #0097ff;
  color: #fff;
}

.btn-edit:hover {
  background-color: #0078cc;
}

.btn-delete {
  background-color: #ff4757;
  color: #fff;
}

.btn-delete:hover {
  background-color: #ff3742;
}

/* 加载和空状态样式 */
.loading, .empty {
  width: 100%;
  padding: 8vw 4vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 3.5vw;
  color: #999;
  background-color: #fff;
  margin-top: 12vw;
  min-height: 40vw;
}

.empty .fa-cutlery {
  font-size: 12vw;
  color: #ddd;
  margin-bottom: 3vw;
}

.btn-add-empty {
  margin-top: 4vw;
  padding: 3vw 6vw;
  background-color: #0097ff;
  color: #fff;
  border: none;
  border-radius: 2vw;
  font-size: 3.5vw;
  cursor: pointer;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  z-index: 2000;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4vw;
}

.modal-content {
  width: 100%;
  max-width: 90vw;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 3vw;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4vw;
  background-color: #0097ff;
  color: #fff;
}

.modal-header h3 {
  font-size: 4.5vw;
  margin: 0;
}

.modal-header .fa-times {
  font-size: 5vw;
  cursor: pointer;
}

.modal-body {
  padding: 4vw;
  max-height: 50vh;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 4vw;
}

.form-group label {
  display: block;
  font-size: 3.5vw;
  color: #333;
  margin-bottom: 2vw;
  font-weight: bold;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 3vw;
  border: 1px solid #ddd;
  border-radius: 1vw;
  font-size: 3.5vw;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #0097ff;
}

.modal-footer {
  display: flex;
  gap: 3vw;
  padding: 4vw;
  background-color: #f8f8f8;
}

.modal-footer button {
  flex: 1;
  height: 10vw;
  border: none;
  border-radius: 2vw;
  font-size: 3.8vw;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel {
  background-color: #ddd;
  color: #666;
}

.btn-save {
  background-color: #38ca73;
  color: #fff;
}

.btn-save:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 响应式适配 */
@media (max-width: 480px) {
  header {
    height: 50px;
    padding: 0 16px;
    font-size: 18px;
  }
  
  header .fa-angle-left {
    font-size: 20px;
  }
  
  header .fa-plus {
    font-size: 18px;
  }
  
  .food-list {
    margin-top: 50px;
    min-height: calc(100vh - 50px - 20px);
  }
  
  .food-item {
    padding: 12px;
    gap: 12px;
  }
  
  .food-item img {
    width: 50px;
    height: 50px;
  }
  
  .food-info-header {
    gap: 8px;
  }
  
  .food-info-header h3 {
    font-size: 14px;
  }
  
  .food-price {
    font-size: 14px;
  }
  
  .food-explain {
    font-size: 12px;
  }
  
  .food-actions {
    gap: 8px;
    margin-top: 4px;
  }
  
  .food-actions button {
    height: 28px;
    font-size: 11px;
    min-width: 60px;
  }
  
  .loading, .empty {
    margin-top: 50px;
    min-height: 200px;
    padding: 40px 20px;
    font-size: 14px;
  }
  
  .wrapper {
    padding-bottom: 20px;
    overflow-x: hidden;
  }
  
  .modal-content {
    max-width: 95vw;
  }
  
  .modal-header h3 {
    font-size: 18px;
  }
  
  .form-group label {
    font-size: 14px;
  }
  
  .form-group input,
  .form-group textarea {
    font-size: 14px;
    padding: 12px;
  }
  
  .modal-footer button {
    height: 40px;
    font-size: 15px;
  }
}
</style> 